<!DOCTYPE html>




<html class="theme-next gemini" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
    
  
  <link href="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.css" rel="stylesheet" type="text/css">




  
  
  
  

  
    
    
  

  
    
      
    

    
  

  

  
    
      
    

    
  

  
    
      
    

    
  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Monda:300,300italic,400,400italic,700,700italic|Roboto Slab:300,300italic,400,400italic,700,700italic|Lobster Two:300,300italic,400,400italic,700,700italic|Source Code Pro:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






  

<link href="https://cdn.staticfile.org/font-awesome/4.6.2/css/font-awesome.css" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=6.0.0" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="http://tva3.sinaimg.cn/crop.206.47.515.515.180/709d5819jw8f4k1tlmnsij20pr0gytdx.jpg?v=6.0.0">


  <link rel="icon" type="image/png" sizes="32x32" href="http://tva3.sinaimg.cn/crop.206.47.515.515.180/709d5819jw8f4k1tlmnsij20pr0gytdx.jpg?v=6.0.0">


  <link rel="icon" type="image/png" sizes="16x16" href="http://tva3.sinaimg.cn/crop.206.47.515.515.180/709d5819jw8f4k1tlmnsij20pr0gytdx.jpg?v=6.0.0">


  <link rel="mask-icon" href="http://tva3.sinaimg.cn/crop.206.47.515.515.180/709d5819jw8f4k1tlmnsij20pr0gytdx.jpg?v=6.0.0" color="#222">





  <meta name="keywords" content="vps, java, python, golang, springmvc">




  


  <link rel="alternate" href="/atom.xml" title="张恒的网络日志" type="application/atom+xml">






<meta name="keywords" content="java, python, go, 技术, 学习笔记, spring">
<meta property="og:type" content="website">
<meta property="og:title" content="张恒的网络日志">
<meta property="og:url" content="http://blog.gavinzh.com/404.html">
<meta property="og:site_name" content="张恒的网络日志">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2020-01-05T08:52:36.912Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="张恒的网络日志">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '6.0.0',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":true,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    fastclick: true,
    lazyload: true,
    tabs: true,
    motion: {"enable":false,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://blog.gavinzh.com/404.html">





  <title>java性能调优 | 张恒的网络日志</title>
  




<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
            (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
          m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
  ga('create', 'UA-98061925-1', 'auto');
  ga('send', 'pageview');
</script>





</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"> <div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">张恒的网络日志</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <h1 class="site-subtitle" itemprop="description">Zhang Heng's WebSite Blog</h1>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://blog.gavinzh.com/2018/08/04/java-performance-tuning/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Gavin Zhang">
      <meta itemprop="description" content>
      <meta itemprop="image" content="https://avatars3.githubusercontent.com/u/5567916">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="张恒的网络日志">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">java性能调优</h2>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-08-04T05:51:00+00:00">2018-08-04</time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/笔记/" itemprop="url" rel="index">
                    <span itemprop="name">笔记</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2018/08/04/java-performance-tuning/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count disqus-comment-count" data-disqus-identifier="2018/08/04/java-performance-tuning/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          
             <span id="/2018/08/04/java-performance-tuning/" class="leancloud_visitors" data-flag-title="java性能调优">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>以下部分内容整理自《分布式Java应用：原理与实践》——林昊</p>
<p>随着系统自身数据量的增长，访问量增加，系统的响应通常会越来越慢，或者是新的功能在性能上无法满足修去，这个时候需要对系统进行性能调优。调优是一个复杂的过程，涉及的方面有：硬件，操作系统，运行环境软件和应用本身。</p>
<a id="more"></a>

<p>调优步骤：</p>
<img src="http://www.plantuml.com/plantuml/svg/u-AALdYnSE7BzlxdctS_tpt_UT-6vrtROXLqxHI04klsFLqtwyM6vYTxPZoVlUxPWdQ5M0Kk7EAwHPdf6ILWVK_NxtxMkUzPm_8NpNkVJzxsSb67GYmNTc64Dg0-Y1J4NB0EL045tPJyyZom3Szch7ywOTdJZWqlzkrxDhNZsRmv4FLOX1LqSrBJ8EvwldloixdpWK9M2a05G6KGDOGrOdMvbGB4xy_ch0BfwfZ01G00">

<p>调优前，首先要做的是衡量系统现状，这也是判断调优结果的依据。衡量系统状态一般包含以下几个方面：</p>
<ol>
<li>单位请求次数</li>
<li>单次请求时间</li>
<li>资源消耗</li>
</ol>
<p>例如A系统目前每秒钟请求次数1000次，平均响应时间为1秒。</p>
<p>在有了系统现状后，可设定调优目标。通常调优目标是根据用户所能接受的响应速度或者系统所拥有的机器以及所支撑的用户量制定出来的。因此通常会设定出调优目标：所有请求要在500ms内返回。</p>
<p>在设定了调优目标后，要做的就是<strong>寻找性能瓶颈</strong>，这一步通常是最难的，可以结合一些工具来找出造成瓶颈点的代码。</p>
<p>找到瓶颈点代码后，通常要分析其需求场景结合一些优化技巧，制定优化策略。优化策略通常也会有多个，如何选择？一般要收益比较高的（优化后的预期效果/优化需要付出的代价）。</p>
<p>优化后，部署项目，检查时候达成目标。如果已经达成，则结束本次调优；如果没有达成，则需要继续寻找瓶颈点，或者考虑之前没有考虑的优化策略，继续优化，直到达成目标。</p>
<h2 id="寻找性能瓶颈"><a href="#寻找性能瓶颈" class="headerlink" title="寻找性能瓶颈"></a>寻找性能瓶颈</h2><p>性能瓶颈的表现一般有资源消耗过多，外部处理系统的性能不足，或者资源消耗不多，但程序响应速度达不到要求。资源一般消耗在CPU，文件IO，网络IO以及内存方面。机器的资源是有限的，当某个资源消耗过多时，通常会造成系统的响应速度慢。</p>
<h3 id="CPU消耗分析"><a href="#CPU消耗分析" class="headerlink" title="CPU消耗分析"></a>CPU消耗分析</h3><p>在Linux中，CPU主要用于中断，内核以及用户进程的任务处理，优先级为中断&gt;内核&gt;用户进程。</p>
<h4 id="重要概念"><a href="#重要概念" class="headerlink" title="重要概念"></a>重要概念</h4><ul>
<li>上下文切换</li>
</ul>
<p>每个CPU（或者多核CPU中的每核CPU）在同一时间通常只能执行一个线程，Linux采用的是抢占式调度，即为每个线程分配一定的执行时间，当到达执行时间、线程中有IO阻塞或者有高优先级线程要执行时，Linux将切换执行的线程，在切换时要存储当前线程的执行状态，并恢复要执行线程的状态，这个过程被称为上下文切换。对于Java应用，典型的是在文件IO操作、网络IO操作、锁等待或者线程Sleep时，当前线程会进入阻塞或者休眠状态，从而触发上下文切换，<strong>上下文切换过多会造成内核占据较多的CPU使用</strong>，使得应用相应速度下降。</p>
<ul>
<li>运行队列</li>
</ul>
<p>每个CPU核都维护了一个可运行的线程队列，例如一个4核的CPU，Java应用中启动了8个线程，且这8个线程都处于可运行状态，那么在分配平均的情况下，每个CPU核运行队列里就会有两个线程。通常而言，系统的<strong>load</strong>主要由CPU的运行队列来决定，假设以上情况维持了一分钟，那么这一分钟系统的load就是2。但<a href="http://www.linuxjournal.com/article/9001" target="_blank" rel="noopener">load是一个复杂的值</a>，因此这也不是绝对的，运行队列值越大，意味着线程要消耗越长对的时间才能执行完。<a href="http://www.ufsdump.org/papers/oscon2009-linux-monitoring.pdf" target="_blank" rel="noopener">Linux System and NetWork performance Monitoring</a> 中建议控制在每个CPU核上的运行队列为1-3个。</p>
<ul>
<li>利用率</li>
</ul>
<p>CPU利用率为CPU在用户进程、内核、中断处理、IO等待以及空闲五个部分使用百分比，这五个值是用来分析CPU消耗情况的关键指标。<a href="http://www.ufsdump.org/papers/oscon2009-linux-monitoring.pdf" target="_blank" rel="noopener">Linux System and NetWork performance Monitoring</a> 中建议用户进程的CPU消耗/内核的CPU消耗的比率在65%-70%/30%-35%左右。</p>
<h4 id="检测命令"><a href="#检测命令" class="headerlink" title="检测命令"></a>检测命令</h4><p>在Linux中，可通过top或者pidstat命令来查看CPU消耗状况。</p>
<ol>
<li>top</li>
</ol>
<p>输入top命令后即可查看CPU的消耗情况，CPU的汇总信息如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">top - 15:16:34 up 728 days,  1:33, 19 users,  load average: 0.39, 0.43, 0.59</span><br><span class="line">Tasks: 576 total,   2 running, 567 sleeping,   5 stopped,   2 zombie</span><br><span class="line">Cpu(s): 14.9%us,  0.7%sy,  0.0%ni, 84.3%id,  0.0%wa,  0.0%hi,  0.0%si,  0.0%st</span><br><span class="line">Mem:  264484524k total, 111250372k used, 153234152k free, 13148064k buffers</span><br><span class="line">Swap: 16777208k total,        0k used, 16777208k free, 68996980k cached</span><br></pre></td></tr></table></figure>

<p>此处，需要关注的是第三行信息，其中 </p>
<ul>
<li>14.9%us 表示用户进程处理所占的百分比</li>
<li>0.7%sy 表示内核线程处理所占的百分比</li>
<li>0.0%ni 表示被nice命令改变优先级的任务所占百分比</li>
<li>84.3%id 表示CPU空闲时间所占的百分</li>
<li>0.0%wa 表示在执行过程中等待IO所占的百分比</li>
<li>0.0%hi 表示硬件中断所占的百分比</li>
<li>0.0%si 表示软件中断所占的百分比</li>
</ul>
<p>对于多个或者多核CPU，上面的显示则会是多个CPU所占用的百分比综合，因此会出现180%us这样的现象。如果需要查看每个核心的消耗情况，可进入top后按 1，就会按核心来显示消耗情况。如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">top - 15:31:12 up 23:49,  1 user,  load average: 0.03, 0.02, 0.00</span><br><span class="line">Tasks: 211 total,   1 running, 210 sleeping,   0 stopped,   0 zombie</span><br><span class="line">%Cpu0  :  0.0 us,  0.3 sy,  0.0 ni, 99.7 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st</span><br><span class="line">%Cpu1  :  0.0 us,  0.0 sy,  0.0 ni,100.0 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st</span><br><span class="line">%Cpu2  :  0.0 us,  0.0 sy,  0.0 ni,100.0 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st</span><br><span class="line">%Cpu3  :  0.0 us,  0.0 sy,  0.0 ni,100.0 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st</span><br><span class="line">KiB Mem :  3050276 total,  1505612 free,   417000 used,  1127664 buff/cache</span><br><span class="line">KiB Swap:  3176444 total,  3176444 free,        0 used.  2324580 avail Mem</span><br></pre></td></tr></table></figure>

<p>默认情况下，top是按照进程来显示CPU消耗的，如果需要按照线程查看，可进入top后按 <code>shift+h</code> ，就会按照线程查看CPU消耗情况。如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">top - 15:39:06 up 23:57,  1 user,  load average: 0.08, 0.06, 0.02</span><br><span class="line">Threads: 357 total,   1 running, 356 sleeping,   0 stopped,   0 zombie</span><br><span class="line">%Cpu(s):  0.0 us,  0.1 sy,  0.0 ni, 99.9 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st</span><br><span class="line">KiB Mem :  3050276 total,  1505032 free,   416576 used,  1128668 buff/cache</span><br><span class="line">KiB Swap:  3176444 total,  3176444 free,        0 used.  2324896 avail Mem </span><br><span class="line"></span><br><span class="line">   PID USER      PR  NI    VIRT    RES    SHR S %CPU %MEM     TIME+ COMMAND                                                                                                                 </span><br><span class="line">  1844 mysql     20   0 1239012 136296  15476 S  0.3  4.5   0:04.47 mysqld                                                                                                                  </span><br><span class="line">  2344 root      20   0  647140  38368  27164 S  0.3  1.3   0:15.53 dockerd                                                                                                                 </span><br><span class="line">  2422 root      20   0  647140  38368  27164 S  0.3  1.3   0:13.78 dockerd</span><br></pre></td></tr></table></figure>

<ol start="2">
<li>pidstat</li>
</ol>
<p>pidstat 是 sysstat 中的工具，要使用 pidstat ，需要先安装 sysstat。</p>
<p>输入 pidstat 1 2，在console上将会每隔1秒输出目前活动进程的CPU消耗情况，共输出2次。</p>
<p>如果想查看某进程中线程的CPU消耗情况，可以输入 pidstat -p pid -t 1 5</p>
<p>总结：当CPU消耗严重时，主要体现在us 、sy 、wa 或hi 的值变高，wa的值是IO等待造成的，hi 的值变高主要是硬件中断造成的，例如网卡接收数据频繁。</p>
<h4 id="java应用的CPU调优"><a href="#java应用的CPU调优" class="headerlink" title="java应用的CPU调优"></a>java应用的CPU调优</h4><p>对于java应用而言，CPU消耗严重主要体现在us 、sy两个值上。</p>
<ol>
<li>us</li>
</ol>
<p>当us值过高时，表示运行的应用消耗了大部分的CPU。在这种情况下，对于Java应用而言，最重要的是找到具体消耗CPU的线程所执行的代码。可采用如下方法。</p>
<p>首先通过Linux命令找到CPU消耗严重的线程及ID，将次ID转为十六进制，之后通过<code>kill -3 javapid</code> 或 <code>jstack pid | grep &#39;nid=ID&#39;</code> 找出具体信息，前面两个命令需要多次使用，以确定找到真实消耗CPU的线程和代码。</p>
<ol start="2">
<li>sy</li>
</ol>
<p>当sy 值高时，表示 Linux花费了太多的时间在上下文切换上，Java应用造成这种情况的原因是启动的线程比较多，且这些线程多数处于要不断阻塞（例如锁等待，IO等待）和执行状态变化过程中，这就导致了操作系统需要不断地切换执行线程，产生大量的上下文切换。</p>
<h3 id="文件IO消耗分析"><a href="#文件IO消耗分析" class="headerlink" title="文件IO消耗分析"></a>文件IO消耗分析</h3><p>Linux在操作文件时，将数据放入文件缓冲区，直到内存不够或系统要释放内存给用户进程使用。因此在查看Linux内存状况时，经常会发现可用（free）的物理内存不多，但是 cached 用了很多，这是Linux提升文件IO速度的一种做法。在这种做法下，如果物理空闲的内存够用，通常只有在写文件和第一次读取文件时才会产生真正的文件IO。</p>
<p>查看进程文件IO还是使用 pidstat 命令：<code>pidstat -d -t -p pid 1 100</code> ，其中，KB_rd/s 表示每秒读取的KB数，KB_WR/s 表示每秒写入的KB数。</p>
<h3 id="网络IO消耗分析"><a href="#网络IO消耗分析" class="headerlink" title="网络IO消耗分析"></a>网络IO消耗分析</h3><p>对于分布式java应用或使用微服务的应用，网络IO的消耗也值得关注。</p>
<p>在Linux中可采用sar来分析网络IO的消耗状况。<code>sar -n ALL 1 2</code> 执行后以1秒为频率一共输出两次网络IO的情况。</p>
<h3 id="内存消耗分析"><a href="#内存消耗分析" class="headerlink" title="内存消耗分析"></a>内存消耗分析</h3><p>Java内存的消耗主要是在JVM堆内存上，在正式环境中，多数Java应用都会讲-Xms和-Xmx设置为相同的值，避免运行期间不断地申请内存。对于java内存消耗状况的分析，我会单独再写。</p>
<p>需要注意的是，在应用启动时设置的-Xmx的值对堆外内存是没有效果的。你可以使用<code>DirectByteBuffer</code>实现对堆外内存的操作，对应java的类为<code>ByteBuffer</code>。</p>
<h3 id="程序执行慢的原因分析"><a href="#程序执行慢的原因分析" class="headerlink" title="程序执行慢的原因分析"></a>程序执行慢的原因分析</h3><p>有些情况是资源消耗不多，但是程序仍然执行慢，这种现象多出现于访问量不是很大，消耗多是应用内耗产生的。原因主要有以下三种。</p>
<ol>
<li>锁竞争激烈</li>
</ol>
<p>例如数据库连接池提供的连接数通常是有限的，假设提供了10个连接，但如果此时有50个 线程要进行数据库操作，那么就会造成另外的40个线程处于等待状态。</p>
<ol start="2">
<li>未充分使用硬件资源</li>
</ol>
<p>例如机器是四核的，但程序都是单线程串行操作，并没有充分发挥硬件资源的作用，此时可以进行优化来充分使用硬件资源，提升程序执行速度。</p>
<ol start="3">
<li>数据量增长</li>
</ol>
<p>例如数据库中单表的数据由100w上涨到了10000w，数据库读写速度大幅度下降。</p>
<p>对于以上情况，可以使用jprofile等商业工具进行分析，从而找到执行耗时比率较大的代码。</p>
<h2 id="调优"><a href="#调优" class="headerlink" title="调优"></a>调优</h2><p>找到系统性能瓶颈后，接下来就是调优了。调优可以从硬件、操作系统、JVM和程序四个方面着手。硬件和操作系统的调优可以参考计算机系统等相关书籍，接下来主要探讨的是JVM和程序方面的调优。</p>
<h3 id="JVM调优"><a href="#JVM调优" class="headerlink" title="JVM调优"></a>JVM调优</h3><p>JVM调优主要是内存管理方面你的调优，包括各个代大小，GC策略等。由于GC会影响应用线程，严重影响性能，这些调优对于应用而言还是很重要的。根据应用的情况选择不同的内存管理策略有些时候能够降低GC导致的应用暂停时间，大幅度地提升应用性能，尤其是对于内存消耗较多的应用。</p>
<h4 id="代大小调优"><a href="#代大小调优" class="headerlink" title="代大小调优"></a>代大小调优</h4><p>在不采用G1（JDK1.7提供的不区分年轻代和老年代的垃圾收集器）的情况下，通常Minor GC会远快于Full GC，因为Minor GC 采用的是标记复制算法，Full GC采用的是标记整理/标记清除算法，后者的复杂度比前者的复杂度高。</p>
<p>在代大小调优上，最关键的参数有以下几点：</p>
<ul>
<li><p>-Xms，-Xmx 通常设置为相同的值，避免运行时要不断地扩展JVM内存空间，这个值决定了Heap所使用的最大空间。</p>
</li>
<li><p>-Xmn 决定了新生代（New Generation）空间的大小。</p>
</li>
<li><p>-XX:SurvivorRatio 是控制新生代Eden、S0、S1三个区域的比率，例如比值是 8:1:1 时，值为8</p>
</li>
<li><p>-XX:MaxTenuringThreshold 控制对象在经历多少司Minor GC 后才转入老年代，通常又将此值成为新生代存活周期，此参数只有在串行GC（-XX:+UseSerialGC）时有效，其他GC方式则有Sun JDK自行决定。</p>
</li>
<li><p>当新生代过小时，Minor GC的次数更加频繁，大对象更容易进入老年代，从而触发Full GC。</p>
</li>
<li><p>当新生代过大时，老年代变小，有可能导致Full GC频繁，Minor GC耗时也会增加。</p>
</li>
<li><p>当Survivor Space（S0/S1）过大时，Minor GC次数增加，大对象不容易进入老年代。过小时，Minor GC次数变少，但大对象更容器直接进入老年代。</p>
</li>
<li><p>当新生代存活周期数增加，对象在Minor GC阶段回收的机会就增加了，但是Survivor Space 更容易被占用。</p>
</li>
</ul>
<h4 id="GC策略调优"><a href="#GC策略调优" class="headerlink" title="GC策略调优"></a>GC策略调优</h4><p>串行GC性能较差，像 Serial 在收集和复制时都是一个线程，Parallel 在收集是多个线程，复制时是一个线程，一般都不会使用Serial  GC。一般情况下，我们使用CMS收集器，使用方式如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">-XX:+UseConcMarkSweepGC  -XX:+UseCMSCompactAtFullCollection -XX:CMSMaxAbortablePrecleanTime=5 -XX:+PrintGCDetails -XX:+PrintGCTimeStamps -XX:+PrintGCApplication-StoppedTime</span><br></pre></td></tr></table></figure>

<h3 id="程序调优"><a href="#程序调优" class="headerlink" title="程序调优"></a>程序调优</h3><h4 id="CPU消耗严重"><a href="#CPU消耗严重" class="headerlink" title="CPU消耗严重"></a>CPU消耗严重</h4><p>当us 高说明执行线程无任何挂起动作，且一直执行，对于这种情况，可以在方法中增加Thread.sleep，释放CPU的执行权</p>
<p>当sy 高说明线程切换太过频繁，最简单的优化就是减少线程数。也可以减少线程间通信，降低锁竞争，或者采用协程代替线程。</p>
<h4 id="IO消耗严重"><a href="#IO消耗严重" class="headerlink" title="IO消耗严重"></a>IO消耗严重</h4><ul>
<li>异步写文件</li>
<li>批量读写</li>
<li>限流</li>
<li>限制文件大小</li>
</ul>
<h4 id="网络IO消耗严重"><a href="#网络IO消耗严重" class="headerlink" title="网络IO消耗严重"></a>网络IO消耗严重</h4><p>限流，限制发送packet的频率。</p>
<h4 id="内存消耗严重"><a href="#内存消耗严重" class="headerlink" title="内存消耗严重"></a>内存消耗严重</h4><ul>
<li>释放不必要的引用</li>
<li>使用对象缓存池</li>
<li>采用合理的缓存时效方法（FIFO,LRU,LFU）</li>
<li>合理使用SoftReference和WeakReference（前者在内存不够用的时候回收，后者在Full GC时立刻回收）</li>
</ul>
<h3 id="资源消耗少，程序运行慢调优"><a href="#资源消耗少，程序运行慢调优" class="headerlink" title="资源消耗少，程序运行慢调优"></a>资源消耗少，程序运行慢调优</h3><h4 id="锁竞争激烈"><a href="#锁竞争激烈" class="headerlink" title="锁竞争激烈"></a>锁竞争激烈</h4><p>容易导致CPU sy，即系统上下文切换频繁导致内核线程运行占比较高</p>
<p>解决方法：</p>
<ol>
<li>使用无阻塞的并发类实现阻塞式的并发类（基于CAS ），例如使用ConcurrentLinkedQueue来代替BlockingQueue。</li>
<li>尽量少用锁</li>
<li>拆分锁</li>
</ol>
<h4 id="未充分使用CPU"><a href="#未充分使用CPU" class="headerlink" title="未充分使用CPU"></a>未充分使用CPU</h4><p>多用并行处理                                         </p>
<h2 id="JVM调优常用参数命令"><a href="#JVM调优常用参数命令" class="headerlink" title="JVM调优常用参数命令"></a>JVM调优常用参数命令</h2><h3 id="输出日志"><a href="#输出日志" class="headerlink" title="输出日志"></a>输出日志</h3><p>在jvm启动参数中加入以下参数</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">// 以下含义分别是 输出GC信息，输出GC简要信息，输出GC详细信息，输出GC的时间信息，输出GC造成的应用暂停时间，将GC日志输出到gc.log文件中</span><br><span class="line">-verbose:gc -XX:+PrintGC -XX:+PrintGCDetails -XX:+PrintGCTimeStamps -XX:+PrintGCApplicationStoppedTime -Xloggc:gc.log</span><br></pre></td></tr></table></figure>

<h3 id="查看运行时状态"><a href="#查看运行时状态" class="headerlink" title="查看运行时状态"></a>查看运行时状态</h3><ul>
<li>jmap</li>
</ul>
<p><strong>-heap</strong></p>
<p>打印heap的概要信息，GC使用算法，heap的配置及使用情况</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">jmap -heap pid</span><br></pre></td></tr></table></figure>

<p>在<code>Heap Configuration</code>参数中，MinHeapFreeRatio对应jvm启动参数-XX:MinHeapFreeRatio设置JVM堆最小空闲比率(default 40)，MaxHeapFreeRatio对应jvm启动参数 -XX:MaxHeapFreeRatio设置JVM堆最大空闲比率(default 70)</p>
<p><strong>-histo</strong></p>
<p>打印堆的对象统计，包括对象数，内存大小等。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">jmap -histo:live pid | grep more</span><br></pre></td></tr></table></figure>

<p>附 - jmap输出中class name非自定义类的说明：</p>
<table>
<thead>
<tr>
<th>BaseType Character</th>
<th>Type</th>
<th>Interpretation</th>
</tr>
</thead>
<tbody><tr>
<td>B</td>
<td>byte</td>
<td>signed byte</td>
</tr>
<tr>
<td>C</td>
<td>char</td>
<td>Unicode character</td>
</tr>
<tr>
<td>D</td>
<td>double</td>
<td>double-precision floating-point value</td>
</tr>
<tr>
<td>F</td>
<td>float</td>
<td>single-precision floating-point value</td>
</tr>
<tr>
<td>I</td>
<td>int</td>
<td>integer</td>
</tr>
<tr>
<td>J</td>
<td>long</td>
<td>long integer</td>
</tr>
<tr>
<td>L;</td>
<td>reference</td>
<td>an instance of class</td>
</tr>
<tr>
<td>S</td>
<td>short</td>
<td>signed short</td>
</tr>
<tr>
<td>Z</td>
<td>boolean</td>
<td>true or false</td>
</tr>
<tr>
<td>[</td>
<td>reference</td>
<td>one array dimension，[I表示int[]</td>
</tr>
</tbody></table>
<ul>
<li>jstat</li>
</ul>
<p><strong>-gc</strong></p>
<p>垃圾回收统计</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">jstat -gc pid</span><br></pre></td></tr></table></figure>

<ul>
<li>S0C：第一个幸存区的大小</li>
<li>S1C：第二个幸存区的大小</li>
<li>S0U：第一个幸存区的使用大小</li>
<li>S1U：第二个幸存区的使用大小</li>
<li>EC：伊甸园区的大小</li>
<li>EU：伊甸园区的使用大小</li>
<li>OC：老年代大小</li>
<li>OU：老年代使用大小</li>
<li>MC：方法区大小</li>
<li>MU：方法区使用大小</li>
<li>CCSC:压缩类空间大小</li>
<li>CCSU:压缩类空间使用大小</li>
<li>YGC：年轻代垃圾回收次数</li>
<li>YGCT：年轻代垃圾回收消耗时间</li>
<li>FGC：老年代垃圾回收次数</li>
<li>FGCT：老年代垃圾回收消耗时间</li>
<li>GCT：垃圾回收消耗总时间</li>
</ul>
<p><em>**-gcutil</em></p>
<p>总结垃圾回收统计</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">jstat -gcutil pid</span><br></pre></td></tr></table></figure>

<ul>
<li>S0：幸存1区当前使用比例</li>
<li>S1：幸存2区当前使用比例</li>
<li>E：伊甸园区使用比例</li>
<li>O：老年代使用比例</li>
<li>M：元数据区使用比例</li>
<li>CCS：压缩使用比例</li>
<li>YGC：年轻代垃圾回收次数</li>
<li>FGC：老年代垃圾回收次数</li>
<li>FGCT：老年代垃圾回收消耗时间</li>
<li>GCT：垃圾回收消耗总时间</li>
</ul>
<h3 id="参考"><a href="#参考" class="headerlink" title="参考"></a>参考</h3><p><a href="http://www.oracle.com/technetwork/cn/java/javase/tech/index.html" target="_blank" rel="noopener">Java SE 技术</a></p>
<p><a href="http://www.oracle.com/technetwork/cn/java/javase/tech/index-jsp-136373-zhs.html" target="_blank" rel="noopener">Java SE HotSpot 概览</a></p>
<p><a href="http://www.oracle.com/technetwork/java/javase/tech/vmoptions-jsp-140102.html?ssSourceSiteId=otncn" target="_blank" rel="noopener">Java HotSpot VM Options</a></p>
<p><a href="http://www.oracle.com/technetwork/cn/java/javaee/tech/index.html" target="_blank" rel="noopener">Java EE7 技术</a></p>
<p><a href="https://docs.oracle.com/javase/7/docs/api/" target="_blank" rel="noopener">Java Platform SE 7 API</a></p>
<p><a href="http://www.oracle.com/technetwork/java/javase/tech/memorymanagement-whitepaper-1-150020.pdf" target="_blank" rel="noopener">Memory Management in the Java HotSpot™ Virtual Machine</a></p>
<p><a href="http://www.oracle.com/technetwork/java/hotspotfaq-138619.html?ssSourceSiteId=otncn" target="_blank" rel="noopener">关于Java HotSpot VM的常见问题解答</a></p>

      
    </div>
    
    
    

    

    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    Gavin Zhang
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://blog.gavinzh.com/2018/08/04/java-performance-tuning/" title="java性能调优">http://blog.gavinzh.com/2018/08/04/java-performance-tuning/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/java/" rel="tag"># java</a>
          
            <a href="/tags/jvm/" rel="tag"># jvm</a>
          
            <a href="/tags/调优/" rel="tag"># 调优</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/07/31/why-the-java-program-take-up-so-much-memory/" rel="next" title="为什么java程序占用那么多内存">
                <i class="fa fa-chevron-left"></i> 为什么java程序占用那么多内存
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/08/05/ReentrantLock-and-Condition-learn/" rel="prev" title="学习Lock中Condition的使用">
                学习Lock中Condition的使用 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="disqus_thread">
        <noscript>
          Please enable JavaScript to view the
          <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a>
        </noscript>
      </div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="https://avatars3.githubusercontent.com/u/5567916" alt="Gavin Zhang">
            
              <p class="site-author-name" itemprop="name">Gavin Zhang</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">129</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">7</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">158</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/jiangmitiao" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:me at gavinzh.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#寻找性能瓶颈"><span class="nav-number">1.</span> <span class="nav-text">寻找性能瓶颈</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#CPU消耗分析"><span class="nav-number">1.1.</span> <span class="nav-text">CPU消耗分析</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#重要概念"><span class="nav-number">1.1.1.</span> <span class="nav-text">重要概念</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#检测命令"><span class="nav-number">1.1.2.</span> <span class="nav-text">检测命令</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#java应用的CPU调优"><span class="nav-number">1.1.3.</span> <span class="nav-text">java应用的CPU调优</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#文件IO消耗分析"><span class="nav-number">1.2.</span> <span class="nav-text">文件IO消耗分析</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#网络IO消耗分析"><span class="nav-number">1.3.</span> <span class="nav-text">网络IO消耗分析</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#内存消耗分析"><span class="nav-number">1.4.</span> <span class="nav-text">内存消耗分析</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#程序执行慢的原因分析"><span class="nav-number">1.5.</span> <span class="nav-text">程序执行慢的原因分析</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#调优"><span class="nav-number">2.</span> <span class="nav-text">调优</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#JVM调优"><span class="nav-number">2.1.</span> <span class="nav-text">JVM调优</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#代大小调优"><span class="nav-number">2.1.1.</span> <span class="nav-text">代大小调优</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#GC策略调优"><span class="nav-number">2.1.2.</span> <span class="nav-text">GC策略调优</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#程序调优"><span class="nav-number">2.2.</span> <span class="nav-text">程序调优</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#CPU消耗严重"><span class="nav-number">2.2.1.</span> <span class="nav-text">CPU消耗严重</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#IO消耗严重"><span class="nav-number">2.2.2.</span> <span class="nav-text">IO消耗严重</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#网络IO消耗严重"><span class="nav-number">2.2.3.</span> <span class="nav-text">网络IO消耗严重</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#内存消耗严重"><span class="nav-number">2.2.4.</span> <span class="nav-text">内存消耗严重</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#资源消耗少，程序运行慢调优"><span class="nav-number">2.3.</span> <span class="nav-text">资源消耗少，程序运行慢调优</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#锁竞争激烈"><span class="nav-number">2.3.1.</span> <span class="nav-text">锁竞争激烈</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#未充分使用CPU"><span class="nav-number">2.3.2.</span> <span class="nav-text">未充分使用CPU</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#JVM调优常用参数命令"><span class="nav-number">3.</span> <span class="nav-text">JVM调优常用参数命令</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#输出日志"><span class="nav-number">3.1.</span> <span class="nav-text">输出日志</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#查看运行时状态"><span class="nav-number">3.2.</span> <span class="nav-text">查看运行时状态</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#参考"><span class="nav-number">3.3.</span> <span class="nav-text">参考</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      
        <div class="back-to-top">
          <i class="fa fa-arrow-up"></i>
          
            <span id="scrollpercent"><span>0</span>%</span>
          
        </div>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2013 &mdash; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Gavin Zhang</span>

  

  
</div>





<div>
	<a href="http://www.beian.miit.gov.cn/" target="_blank">陕ICP备17010002号-1</a>
</div>





        




  <script type="text/javascript">
    (function() {
      var hm = document.createElement("script");
      hm.src = "//tajs.qq.com/stats?sId=61868582";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <div style="display: none;">
    <script src="//s95.cnzz.com/z_stat.php?id=1261805793&web_id=1261805793" language="JavaScript"></script>
  </div>



        
      </div>
    </footer>

    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>





  



  






  













  
  
    <script type="text/javascript" src="https://cdn.staticfile.org/jquery/3.4.1/jquery.min.js"></script>
  

  
  
    <script type="text/javascript" src="https://cdn.staticfile.org/fastclick/1.0.6/fastclick.js"></script>
  

  
  
    <script type="text/javascript" src="https://cdn.staticfile.org/jquery.lazyload/1.9.1/jquery.lazyload.min.js"></script>
  

  
  
    <script type="text/javascript" src="https://cdn.staticfile.org/velocity/2.0.5/velocity.min.js"></script>
  

  
  
    <script type="text/javascript" src="https://cdn.staticfile.org/velocity/2.0.5/velocity.min.js"></script>
  

  
  
    <script type="text/javascript" src="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.0.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.0.0"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=6.0.0"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=6.0.0"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.0.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.0.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.0.0"></script>



  


  

    
      <script id="dsq-count-scr" src="https://zhang-hengs-website-blog.disqus.com/count.js" async></script>
    

    
      <script type="text/javascript">
        var disqus_config = function () {
          this.page.url = 'http://blog.gavinzh.com/2018/08/04/java-performance-tuning/';
          this.page.identifier = '2018/08/04/java-performance-tuning/';
          this.page.title = 'java性能调优';
        };
        var d = document, s = d.createElement('script');
        s.src = 'https://zhang-hengs-website-blog.disqus.com/embed.js';
        s.setAttribute('data-timestamp', '' + +new Date());
        (d.head || d.body).appendChild(s);
      </script>
    

  




	





  














  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("EhAMmIXTRGtethTcgYwA9afH-gzGzoHsz", "jzP1TaBhMleAUgPLXyB0h8oQ");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  
  

  
  


  
  <script type="text/javascript" src="/js/src/js.cookie.js?v=6.0.0"></script>
  <script type="text/javascript" src="/js/src/scroll-cookie.js?v=6.0.0"></script>


  

</body>
</html>
